package org.itboys.mobile.service.mysql.mobile.score;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.kitchen.conmon.Finals;
import org.itboys.kitchen.entity.mysql.order.KitchenOrder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.score.SundayScoreRecordMapper;
import org.itboys.mobile.dto.score.SundayScoreRecordDto;
import org.itboys.mobile.entity.mysql.score.SundayScore;
import org.itboys.mobile.entity.mysql.score.SundayScoreConfig;
import org.itboys.mobile.entity.mysql.score.SundayScoreRecord;
import org.itboys.mobile.service.mongo.mobile.SundayMobileMemberService;
import org.itboys.mobile.service.mysql.web.score.SundayScoreConfigService;
import org.itboys.mongodb.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.provider.Sun;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：zzq
 * 日期：2017年5月10日
 * 描述：圣代_积分_service
 */
@Service
public class SundayMobileScoreService extends BaseMySqlService<SundayScore>{
    @Autowired
    private SundayScoreRecordMapper scoreRecordMapper;
    @Autowired
    private SundayScoreConfigService configService;
    @Autowired
    private SundayMobileMemberService memberService;
    /**
     * 查找用户积分主表
     * @param memberId
     * @return
     */
    @Transactional
    public SundayScore findOne(Long memberId){
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        SundayScore score=null;
        List<SundayScore> scores=super.select(param);
        if(ListUtil.isNotNull(scores)){
            score=scores.get(0);
        }else {
            score=new SundayScore(memberId);
            super.insert(score);
            score=super.find(score.getId());
        }
        return score;
    }


    /**
     * 获取用户版上，积分页面需要的整页数据.
     * @param request
     * @param memberId
     * @param type，1签到页，2,我的积分页(含积分记录，当pageNumber>1时，不会请求积分页其他数据)
     * @return
     */
    public Map<String,Object>  selectMobileScore(HttpServletRequest request,Long memberId,Integer type){
        Map<String,Object> result=new HashMap<String,Object>();
        Map<String,Object> param=new HashMap<String,Object>();
        Integer pageNumber= Integer.valueOf((String) request.getParameter("pageNumber")) ;

        BigDecimal ableScore= memberService.getMemberFinance(memberId,null).getScore();

        if(type==1){
            //加载总积分
           // result.put("totalScore",findOne(memberId).getTotalScore());
            result.put("totalScore",ableScore);

            //加载签到配置积分
            result.put("signScore",configService.findOne(null).getSignScore());
            //加载总签到天数
            param.clear();
            param.put("memberId",memberId);
            param.put("type", SundayCommonConstants.SCORE_TYPE_SIGN);
            result.put("totalSignDay",scoreRecordMapper.count(param));
            //加载当天是否签到
            result.put("isSign",isSign(memberId));
            return result;
        }else if(type==2){
            //总签到天数
            result.put("totalSignDay",null);
            //加载总积分
            result.put("totalScore",null);
            if(pageNumber<=1){
                //加载总签到天数
                param.clear();
                param.put("memberId",memberId);
                param.put("type", SundayCommonConstants.SCORE_TYPE_SIGN);
                result.put("totalSignDay",scoreRecordMapper.count(param));
                //加载总积分
               // result.put("totalScore",findOne(memberId).getTotalScore());
                result.put("totalScore",ableScore);
            }
            //加载积分记录
            param.clear();
            param=ParamUtil.packageMysqlPageParam(request);
            param.put("memberId",memberId);
            List<SundayScoreRecordDto>recordDtos=packageMuilt(scoreRecordMapper.select(param));
            result.put("records",recordDtos);
            return result;
        }

       return result;
    }

    /**
     * 生成积分交易记录
     * @param orderNo
     * @param thisScore
     * @param type
     * @param memberId
     */
    @Transactional
    public void generateRecord2(String orderNo,BigDecimal thisScore, Integer type, Long memberId){
        //本次需要增加/或扣减的值
       // BigDecimal thisScore = null;
        String msg="";
        SundayScoreConfig config=configService.findOne(null);
      //  logger.info("--config--"+config.getShoppingScore());
        logger.info("--thisScore--"+thisScore);
        if(type== SundayCommonConstants.SCORE_TYPE_REWARD){
            //购物获得
            msg="在线下单奖励，";
            //thisScore=thisScore.multiply(config.getShoppingScore());
        }else  if(type==SundayCommonConstants.SCORE_TYPE_BUY){
            //购物抵扣
            msg="积分兑换,订单编号："+orderNo;
            thisScore=thisScore.multiply(new BigDecimal("-1"));
        }else if(type==SundayCommonConstants.SCORE_TYPE_SIGN){
            if(isSign(memberId)==1){
                throw new ErrorException("当天已经签到");
            }
            //签到获得
            msg="每日签到奖励";
            //thisScore=config.getSignScore();
        }
        SundayScore score=findOne(memberId);
        BigDecimal totalScore = score.getTotalScore();
        BigDecimal ableScore = score.getAbleScore();
        totalScore=totalScore.add(thisScore);
        ableScore=ableScore.add(thisScore);
        score.setTotalScore(totalScore);
        score.setAbleScore(ableScore);
        super.update(score);
        SundayScoreRecord record=new SundayScoreRecord(memberId,score.getId(),thisScore,type,msg);
        scoreRecordMapper.insert(record);

    }

    /**
     * 判断用户当天是否签到
     * @param memberId
     * @return
     */
    public Integer isSign(Long memberId){
        Date date=new Date();
        Map<String,Object> param=new HashMap<String,Object>();
        Date now=new Date();
        now.setHours(0);
        now.setMinutes(0);
        now.setSeconds(0);
       // Long beginOfDate=now.getTime();
        param.put("beginOfDate", TimeUtils.formatToTime(now));
        now.setHours(23);
        now.setMinutes(59);
        now.setSeconds(59);
       // Long endOfDate = now.getTime();
        param.put("endOfDate",TimeUtils.formatToTime(now));
        param.put("memberId",memberId);
        List<SundayScoreRecord> records=scoreRecordMapper.select(param);
        if(ListUtil.isNotNull(records)){
            return 1;
        }
        return 0;
    }
    /**
     * 组装DTO
     */
    public List<SundayScoreRecordDto> packageMuilt(List<SundayScoreRecord> records){
        List<SundayScoreRecordDto> dtos = new ArrayList<SundayScoreRecordDto>();
        for(SundayScoreRecord record:records){
            dtos.add(new SundayScoreRecordDto(record.getId(), record.getCreateTime(),record.getCreateDate(),
                    record.getScore(), record.getType(), record.getRemark()));
        }
        return  dtos;
    }
}
